package com.binlog.core.handler;

import com.binlog.config.BinLogDbProperty;
import com.binlog.config.BinLogDbPropertys;
import com.binlog.module.BinLogItem;
import com.binlog.module.DatebaseInfo;
import com.binlog.util.MysqlUtils;
import com.binlog.util.SpringContextUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * Common backups
 *
 * @description: 备份类
 * @author: chenyj
 * @date 2023 -11-10 14:47:24
 */
@Slf4j
public abstract class CommonBackups extends BackupInit implements Backups {

    private AtomicInteger count = new AtomicInteger(0);

    /**
     * 执行插入备份
     * @param binLogItem
     */
    @Override
    public void insertHandle(BinLogItem binLogItem) {
        if (!backup()) {
            return;
        }
        execute(binLogItem);
    }

    /**
     * 执行更新备份
     * @param binLogItem
     */
    @Override
    public void updateHandle(BinLogItem binLogItem) {
        if (!backup()) {
            return;
        }
        execute(binLogItem);
    }

    /**
     * 执行删除备份
     * @param binLogItem
     */
    @Override
    public void deleteHandle(BinLogItem binLogItem) {
        if (!backup()) {
            return;
        }
        execute(binLogItem);
    }

    private void execute(BinLogItem binLogItem) {
        log.info("{}-开始备份:{}", count.incrementAndGet(), binLogItem.generateSQL());
        init(binLogItem.getTable(), binLogItem.getSchema(), getDatebaseInfo());
        MysqlUtils.executBackSql(binLogItem.generateSQL(), binLogItem.getSchema());
    }

    /**
     * 是否开启备份
     * @return
     */
    public boolean backup() {
        return null != getDatebaseInfo() && SpringContextUtils.getBean(BinLogDbPropertys.class).getBackupsDatasource() != null && getBinLogDbProperty().isBackupsDatasource();
    }

    public abstract DatebaseInfo getDatebaseInfo();

    public abstract BinLogDbProperty getBinLogDbProperty();
}
